<?php

/**
 * Msa_AgendaObject - Gestion des agendas utilisateur
 *
 * @package
 * @author Alexis Eric, 
 * Erra Prod. http://www.erraprod.com
 * @copyright Copyright (c) 2012 - Erra Prod
 * @access public
 */
class Msa_AgendaObject extends Erra_Fields_Base_Object {

    function __construct($objectId, $buildArgs = null) {
        parent::__construct($objectId, $buildArgs);
        $nom_agenda = Erra_Fields_Text::create('nom_agenda')
                ->setDescription("Nom de l'agenda *")
                ->setInAdminList(true)
                ->setDatabaseType('VARCHAR', 128)
                ->setSize(70);

        $email = Erra_Fields_Text::create('email')
                ->setDatabaseType('VARCHAR', 256)
                ->setDescription('Adresse e-mail');

        $telephone_portable = Erra_Fields_Text::create('telephone_portable')
                ->setDatabaseType('VARCHAR', 32)
                ->setDescription('Téléphone portable');

        $location = Erra_Fields_ComboBox::create('location')
                ->fill(Msa_LocationObject::getLocationArray())
                ->setInAdminList(true)
                ->setDatabaseType('INT', 8)
                ->setDescription('Rattaché à');

        $disponible_sur_internet = Erra_Fields_ComboBox::create('disponible_sur_internet')
                ->setDescription('Disponible sur Internet ?')
                ->setInAdminList(true)
                ->setDatabaseType('TINYINT')
                ->fill(array(0 => 'Non', 1 => 'Oui'));

        $nom_internet = Erra_Fields_Text::create('nom_internet')
                ->setDescription("Nom de l'agenda sur Internet")
                ->setDatabaseType('VARCHAR', 128)
                ->setSize(70);

        $date_creation = Erra_Fields_Hidden::create('date_creation')
                ->setDatabaseType('INT', 16)
                ->setValue(time());

        $accessArray = Access_AccessObject::getAccessTree();
        $acces = Erra_Fields_Tree::create('access')
                ->setDescription('Accès')
                ->setDatabaseType('TEXT')
                ->fill($accessArray);

        $agenda_color = Erra_Fields_Color::create('agenda_color')
                ->setDatabaseType('VARCHAR', 8)
                ->setValue(random_color())
                ->setDescription("Couleur de l'agenda");



        $prestationArray = Msa_PrestationObject::getPrestationTree();
        $prestation = Erra_Fields_Tree::create('prestation')
                ->setDescription('Prestation')
                ->setDatabaseType('TEXT')
                ->fill($prestationArray);

        $this->addFields($nom_agenda, $email, $telephone_portable, $location, $disponible_sur_internet, $nom_internet, $agenda_color, $date_creation, $acces, $prestation);
        $this->addAttribute('class', 'maclasse');
        $this->setDescription('Liste des agendas');
        global $licence_object;
        Access_AuthObject::authenticate();
        if ($licence_object->max_agendas - $this->getRealUsedAgendas() <= 0) {
            $this->setCrud('RUD');
        } else {
            $this->setCrud('CRUD');
        }
    }

    public function getRealUsedAgendas() {
        $query = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_agendas FROM msa_agendaobject');
        if (Erra_Core_DatabasePdo::rowCount()) {
            $result = $query->fetch();
            return $result->num_agendas;
        }
        return 0;
    }

    /**
     * postInit() - Calcul des prestation et des accès associés à cet agenda
     */
    public function postInit() {
        $resultArray = array();
        $agendas = Erra_Core_DatabasePdo::SELECT('SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id=' . $this->getId());
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $agendas->fetch()) {
                $resultArray[] = $row->prestation_id;
            }
        }
        $this->prestation->setRawData($resultArray);
        $resultAccessArray = array();
        $accesses = Erra_Core_DatabasePdo::SELECT('SELECT access_id FROM back_agenda_access WHERE agenda_id=' . $this->getId());
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $accesses->fetch()) {
                $resultAccessArray[] = $row->access_id;
            }
        }
        $this->access->setRawData($resultAccessArray);
    }

    /**
     * getAgendaLocations() - Créé un tableau associatif de l'id des agenda avec leurs lieux (utile pour le calendrier)
     * 
     * @param type $agendaList
     * @return type
     */
    public static function getAgendaLocations($agendaList) {
        $resultArray = array();
        if (is_array($agendaList)) {
            $query = Erra_Core_DatabasePdo::SELECT('SELECT msa_agendaobject.id, nom FROM msa_locationobject, msa_agendaobject WHERE msa_locationobject.id=msa_agendaobject.location AND msa_agendaobject.id IN(' . implode(',', $agendaList) . ')');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $query->fetch()) {
                    $resultArray[$row->id] = $row->nom;
                }
            }
        }
        return json_encode($resultArray);
    }

    /**
     * getEnabledAgendaArray() Retourne un tableau des id des agendas actifs
     * 
     * @return type
     */
    public static function getEnabledAgendaArray() {
        $tree_items = array();
        if (!Access_ControlObject::isSuperAdmin()) {
            $user_infos = Erra_Persistance_Session::get('login_infos');
            $authorizedAgendas = Erra_Core_DatabasePdo::SELECT('SELECT agenda_id FROM back_agenda_access WHERE access_id="' . $user_infos->id . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $authorizedAgendas->fetch()) {
                    $tree_items[] = $row->agenda_id;
                }
            }
        } else {
            $authorizedAgendas = Erra_Core_DatabasePdo::SELECT('SELECT DISTINCT id AS agenda_id FROM msa_agendaobject');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $authorizedAgendas->fetch()) {
                    $tree_items[] = $row->agenda_id;
                }
            }
        }
        return $tree_items;
    }

    /**
     * getAuthorizedAgendaList() - Retourne une liste associative des agendas autorisés
     * 
     * @return type
     */
    public static function getAuthorizedAgendaList() {
        $user_infos = Erra_Persistance_Session::get('login_infos');
        $list_item = array();
        $authorizedAgendas = Erra_Core_DatabasePdo::SELECT('SELECT agenda_id, nom_agenda FROM back_agenda_access, msa_agendaobject WHERE access_id="' . $user_infos->id . '" AND msa_agendaobject.id=agenda_id');
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $authorizedAgendas->fetch()) {
                $list_item[$row->agenda_id] = $row->nom_agenda;
            }
        }
        return $list_item;
    }

    /**
     * getAuthorizedAgendaTree() - Retourne un arbre avec les agendas autorisés
     * 
     * @param type $forceFullTree
     * @return type
     */
    public static function getAuthorizedAgendaTree($forceFullTree = false) {
        $user_infos = Erra_Persistance_Session::get('login_infos');
        $tree_items = array();
        $authorizedAgendas = Erra_Core_DatabasePdo::SELECT('SELECT agenda_id FROM back_agenda_access WHERE access_id="' . $user_infos->id . '"');
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $authorizedAgendas->fetch()) {
                $tree_items[] = $row->agenda_id;
            }
        }

        $orphanArray = array();
        $locationArray = array();
        // On récupère la liste des etablissements
        $locations = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_locationobject');
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $locations->fetch()) {
                if (is_numeric($row->id)) {
                    $locationArray[$row->id] = array('title' => $row->nom, 'children' => array());
                }
            }
        }
        // On récupère la liste des agendas
        $agendas = Erra_Core_DatabasePdo::SELECT('SELECT nom_agenda, id, location FROM msa_agendaobject');
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $agendas->fetch()) {
                if (Access_ControlObject::isSuperAdmin() || $forceFullTree == true || (in_array($row->id, $tree_items))) {
                    // Attach current agenda to location or set it as an orphan
                    if (is_numeric($row->location) && isset($locationArray[$row->location])) {
                        $locationArray[$row->location]['children'][] = array('title' => $row->nom_agenda, 'key' => $row->id);
                    } else {
                        $orphanArray[] = array('title' => $row->nom_agenda, 'key' => $row->id);
                    }
                }
            }
        }
        // Le code commenté filtre les agendas en fonction
        //if (!(Access_ControlObject::isSuperAdmin() || $forceFullTree == true)) {
        foreach ($locationArray as $key => $locationData) {
            if (empty($locationData['children'])) {
                unset($locationArray[$key]);
            }
        }
        //}
        // On mélange le tableau des agendas rattachés à un lieu et des agendas oprhelins
        $children = array_merge($locationArray, $orphanArray);
        return array('title' => 'Agendas',
            'expand' => true, 'children' => $children);
    }

    /** 
     * getAgendaArray() - Retourne la liste des agenda en Array
     */
    public static function getAgendaArray() {
        $agendas = array();
        $agenda_list = Erra_Core_DatabasePdo::SELECT("SELECT * from msa_agendaobject");
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $agenda_list->fetch()) {
                $agendas[$row->id] = $row->nom_agenda;
            }
        }
        return $agendas;
    }

    /**
     * getAgendaArrayJS() - Retourne la liste des agendas autorisés pour un accès, listés dans leur ordre naturel
     * 
     * @param type $webView TRUE si on veut seulement récuperer eles agendas autorisés sur le web
     * @return type
     */
    public static function getAgendaArrayJS($webView = false, $json_encode = true) {
        $resultArray = array();
        $authorized_array = Config_ConfigObject::get('afficher_agendas');
        foreach ($authorized_array as $key => $item) {
            if (!is_numeric($item)) {
                unset($authorized_array[$key]);
            }
        }
        // On récupère la liste des agendas autorisés en se basant sur les informations de login
        if (is_array($authorized_array) && count($authorized_array)) {
            $extraClause = ($webView == 'web') ? ' AND msa_agendaobject.disponible_sur_internet=1 ' : '';
            $login_infos = Erra_Persistance_Session::get('login_infos');
            if (is_object($login_infos) && is_numeric($login_infos->id)) {
                $agendas = Erra_Core_DatabasePdo::SELECT('SELECT * FROM  msa_agendaobject WHERE id IN (' . implode(',', $authorized_array) . ')  ' . $extraClause);

                if (Erra_Core_DatabasePdo::rowCount()) {
                    while ($row = $agendas->fetch()) {
                        $resultArray[] = $row->nom_agenda;
                    }
                }
            }
        }
        return ($json_encode) ? json_encode($resultArray) : $resultArray;
    }

    /**
     * getAgendaIdArrayJS() - On récupère la liste des agendas autorisés pour un utilisateur, listés dans leur ordre naturel
     * 
     * @param type $webView TRUE si on veut seulement récuperer eles agendas autorisés sur le web
     * @return type
     */
    public static function getAgendaIdArrayJS($webView = false, $json_encode = true) {
        $resultArray = array();
        $authorized_array = Config_ConfigObject::get('afficher_agendas');
        foreach ($authorized_array as $key => $item) {
            if (!is_numeric($item)) {
                unset($authorized_array[$key]);
            }
        }
        // On récupère la liste des agendas autorisés en se basant sur les informations de login
        if (is_array($authorized_array) && count($authorized_array)) {
            $extraClause = ($webView == 'web') ? ' AND msa_agendaobject.disponible_sur_internet=1 ' : '';
            $login_infos = Erra_Persistance_Session::get('login_infos');
            if (is_object($login_infos) && is_numeric($login_infos->id)) {
                $agendas = Erra_Core_DatabasePdo::SELECT('SELECT id FROM  msa_agendaobject WHERE id IN (' . implode(',', $authorized_array) . ') ' . $extraClause);
                if (Erra_Core_DatabasePdo::rowCount()) {
                    while ($row = $agendas->fetch()) {
                        $resultArray[] = $row->id;
                    }
                }
            }
        }
        return ($json_encode) ? json_encode($resultArray) : $resultArray;
    }

    /**
     * getAgendaCount() - Calcul du nombre total d'agendas
     * 
     * @return type
     */
    public static function getAgendaCount() {
        $count = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS num_agendas FROM msa_agendaobject')->fetch();
        return $count->num_agendas;
    }

    public static function getAgendaColors() {
        $agendas = Erra_Core_DatabasePdo::SELECT('SELECT id, agenda_color FROM  msa_agendaobject');
        $resultArray = array();
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $agendas->fetch()) {
                $resultArray[$row->id] = $row->agenda_color;
            }
        }
        return $resultArray;
    }

    /* public static function getAgendaPrestations() {
      $resultArray = array();
      $agendaIds = Erra_Core_DatabasePdo::SELECT('SELECT DISTINCT id FROM msa_agendaobject');
      if (Erra_Core_DatabasePdo::rowCount()) {
      while ($agendaRow = $agendaIds->fetch()) {
      $agendas = Erra_Core_DatabasePdo::SELECT('SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id=' . $agendaRow->id);
      if (Erra_Core_DatabasePdo::rowCount()) {
      while ($row = $agendas->fetch()) {
      if (!isset($resultArray[$agendaRow->id])) {
      $resultArray[$agendaRow->id] = array();
      }
      $resultArray[$agendaRow->id][] = $row->prestation_id;
      }
      }
      }
      }
      return json_encode($resultArray);
      } */
}
